<?php

/**
 * 个人中心
 */
namespace Weixin\Controller;

use Common\Controller\WeixinbaseController;

class UserController extends WeixinbaseController {
	protected $wx_bank_invite;
	protected $wx_validate_record;
	protected $wx_article;
	protected $page_size; // 分页大小
	public function _initialize() {
		$this->wx_bank_invite = D ( "Common/BankInvite" );
		$this->wx_validate_record = D ( "Common/ValidateRecord" );
		$this->wx_article = D ( "Common/Article" );
		$this->page_size = 15;
		parent::_initialize ();
	}
	/**
	 * 加盟我们
	 */
	public function join() {
		$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
		$info = $this->wx_invite->where ( array (
				"uid" => $uid 
		) )->find ();
		parent::dict_radio ( array (
				array (
						'code' => 'USER_SEX',
						'name' => 'sex',
						'text' => '性别' 
				) 
		) );
		if (empty ( $info )) {
			$this->display ();
		} else {
			$state = intval ( $info ['state'] );
			switch ($state) {
				case 1 :
					$this->redirect ( "User/shenhezhong" );
					break;
				case 2 :
					$this->redirect ( "Coms/center" );
					break;
				case 3 :
					$this->redirect ( "User/jinyong" );
					break;
				default :
					$this->redirect ( "Coms/index" );
			}
		}
	}
	/**
	 * 加盟审核中
	 */
	public function shenhezhong() {
		$this->display ();
	}
	
	/**
	 * 用户被禁用
	 */
	public function jinyong() {
		$this->display ();
	}
	/**
	 * 获取手机验证码
	 */
	public function getCode() {
		$mobile_phone = trim ( $_POST ['mobile_phone'] );
		if (empty ( $mobile_phone )) {
			$result ['state'] = - 1;
			$result ['msg'] = "手机号不能为空!";
		} else if (! $this->is_mobile_phone ( $mobile_phone )) {
			$result ['state'] = - 1;
			$result ['msg'] = "手机号格式不正确!";
		} else if ($this->check_validate_record_exist ( $mobile_phone )) {
			// 获取数据库中的验证记录
			$record = $this->get_validate_record ( $mobile_phone );
			/**
			 * 检查是过了限制发送短信的时间
			 */
			$last_send_time = $record ['last_send_time'];
			$expired_time = $record ['expired_time'];
			$create_time = $record ['create_time'];
			$count = $record ['count'];
			// 每天每个手机号最多发送的验证码数量
			$max_sms_count = 10;
			// 发送最多验证码数量的限制时间，默认为24小时
			$max_sms_count_time = 60 * 60 * 24;
			if ((time () - $last_send_time) < 60) {
				$result ['state'] = - 1;
				$result ['msg'] = "每60秒内只能发送一次短信验证码，请稍候重试!";
			} else if (time () - $create_time < $max_sms_count_time && $record ['count'] > $max_sms_count) {
				$result ['state'] = - 1;
				$result ['msg'] = "您发送验证码太过于频繁，请稍后重试!";
			} else {
				$count ++;
			}
		}
		// 设置为空
		if (APP_DEBUG) {
			/**
			 * *测试模式不发送短信验证码
			 */
			$mobile_code = 888888;
			$res = true;
		} else {
			$mobile_code = $this->rand_number ( 6 );
			$res = $this->sendSMS ( $mobile_phone, $mobile_code );
		}
		if ($res) {
			if (! isset ( $count )) {
				$ext_info = array (
						"count" => 1 
				);
			} else {
				$ext_info = array (
						"count" => $count 
				);
			}
			// 保存手机号码到SESSION中
			$_SESSION ["mobile_phone"] = $mobile_phone;
			// 保存验证信息
			$this->save_validate_record ( $mobile_phone, $mobile_code, "mobile_phone", time (), time () + 30 * 60, $ext_info );
			$result ['state'] = 1;
		} else {
			$result ['state'] = - 1;
			$result ['msg'] = "短信验证码发送失败!";
		}
		echo json_encode ( $result, true );
	}
	/**
	 * 从数据库中获取验证记录信息，会将ext_info数组解析与结果合并
	 *
	 * @param string $key        	
	 * @return boolean|array:
	 */
	function get_validate_record($key) {
		$row = $this->wx_validate_record->where ( array (
				"record_key" => $key 
		) )->find ();
		if ($row == false) {
			return false;
		}
		$row ['ext_info'] = unserialize ( $row ['ext_info'] );
		$record = array (
				// 验证代码
				"record_key" => $row ['record_key'],
				// 验证代码
				"record_code" => $row ['record_code'],
				// 业务类型
				"record_type" => $row ['record_type'],
				// 开始时间
				"last_send_time" => $row ['last_send_time'],
				// 过期时间
				"expired_time" => $row ['expired_time'],
				// 创建时间
				"create_time" => $row ['create_time'] 
		);
		$record = array_merge ( $record, $row ['ext_info'] );
		return $record;
	}
	/**
	 * 保存一个验证记录到数据库，如果存在则更新
	 * 
	 * @param string $key
	 *        	验证标识
	 * @param string $code
	 *        	验证值
	 * @param string $type
	 *        	验证类型
	 * @param datetime $expired_time
	 *        	过期时间
	 * @param array $ext_info
	 *        	扩展信息
	 */
	function save_validate_record($key, $code, $type, $last_send_time, $expired_time, $ext_info = array()) {
		$record = array (
				// 标识
				"record_key" => $key,
				// 验证代码
				"record_code" => $code,
				// 业务类型
				"record_type" => $type,
				// 业务类型
				"last_send_time" => $last_send_time,
				// 过期时间
				"expired_time" => $expired_time,
				// 扩展信息
				"ext_info" => serialize ( $ext_info ) 
		);
		$exist = $this->check_validate_record_exist ( $key );
		if (! $exist) {
			// 记录创建时间
			$record ["create_time"] = time ();
			/* insert */
			$this->wx_validate_record->add ( $record );
		} else {
			/* update */
			$this->wx_validate_record->save ( $record );
		}
	}
	/**
	 * 检查验证记录在数据库中是否已经存在
	 * 
	 * @param string $key        	
	 * @return boolean
	 */
	function check_validate_record_exist($key) {
		$count = $this->wx_validate_record->where ( array (
				"record_key" => $key 
		) )->count ();
		if ($count > 0) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 加盟我们提交
	 */
	public function join_post() {
		$name = $_POST ['name'];
		$mobile = $_POST ['mobile'];
		$mobile_code = $_POST ['mobile_code'];
		$card = $_POST ['card'];
		$sex = $_POST ['sex'];
		
		if (empty ( $name ) || empty ( $mobile ) || empty ( $mobile_code ) || empty ( $card ) || empty ( $sex )) {
			$result ['state'] = - 1;
			$result ['msg'] = "必填信息不能为空!";
		} else {
			if (! $this->is_mobile_phone ( $mobile )) {
				$result ['state'] = - 1;
				$result ['msg'] = "手机号格式不正确!";
			} else if (! $this->validation_filter_id_card ( $card )) {
				$result ['state'] = - 1;
				$result ['msg'] = "身份证号格式不正确!";
			} else {
				$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
				$record = $this->get_validate_record ( $mobile );
				$mobile_phone = $_SESSION ["mobile_phone"];
				/* 手机验证码检查 */
				if (empty ( $mobile_code )) {
					$result ['state'] = - 1;
					$result ['msg'] = "手机验证码不能为空!";
				} 				// 检查发送短信验证码的手机号码和提交的手机号码是否匹配
				else if ($mobile != $mobile_phone) {
					$result ['state'] = - 1;
					$result ['msg'] = "发送短信验证码的手机号码和提交的手机号码不匹配!";
				} 				// 检查验证码是否正确
				else if ($record ['record_code'] != $mobile_code) {
					$result ['state'] = - 1;
					$result ['msg'] = "手机验证码不正确!";
				} 				// 检查过期时间
				else if ($record ['expired_time'] < time ()) {
					$result ['state'] = - 1;
					$result ['msg'] = "验证码已经过期!";
				} else {
					$info = $this->wx_invite->where ( array (
							"mobile" => $mobile 
					) )->find ();
					$invite ['name'] = $name;
					$invite ['uid'] = $uid;
					$invite ['sex'] = $sex;
					$invite ['card'] = $card;
					// 申请加盟成功后 扫码用户添加推广者ID
					$promoters_id = $this->wx_user->where ( array (
							"uid" => $uid ) ) ->getField("promoters_id");
					$invite ['promoters_id'] = $promoters_id;
					if (empty ( $info )) {
						$invite ['mobile'] = $mobile;
						$invite ['created_time'] = time ();
						$invite ['state'] = 2;
						/**
						 * 默认审核通过，默认申请中仅需注释该行即可*
						 */
						$res = $this->wx_invite->add ( $invite );
					} else {
						$invite ['id'] = $info ['id'];
						$res = $this->wx_invite->save ( $invite );
					}
					if ($res != false) {
						$result ['state'] = 1;
					} else {
						$result ['state'] = - 1;
						$result ['msg'] = "加盟失败!";
					}
				}
			}
		}
		echo json_encode ( $result, true );
	}
	/**
	 * 个人中心
	 */
	public function index() {
		$this->check_is_invite ();
		$this->assign ( "data", $this->getUserInfo () );
		$this->display ();
	}
	/**
	 * 个人信息
	 */
	public function user_detail() {
		$this->check_is_invite ();
		
		$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
		$data = $this->wx_invite->where ( array (
				"uid" => $uid 
		) )->find ();
		$this->assign ( "data", $data );
		
		parent::dict_select ( array (
				array (
						'code' => 'USER_SEX',
						'name' => 'sex',
						'text' => '性别',
						'value' => $data ['sex'] 
				) 
		) );
		$this->display ();
	}
	
	/**
	 * 个人信息提交
	 */
	public function user_detail_post() {
		$this->check_is_invite ();
		$id = I ( "post.id", 0, 'intval' );
		$name = $_POST ['name'];
		$card = $_POST ['card'];
		$mobile = $_POST ['mobile'];
		$sex = $_POST ['sex'];
		if (empty ( $id ) || empty ( $name ) || empty ( $card ) || empty ( $mobile ) || empty ( $sex )) {
			$result ['state'] = - 1;
			$result ['msg'] = "必填信息不能为空!";
		} else {
			if (! $this->validation_filter_id_card ( $card )) {
				$result ['state'] = - 1;
				$result ['msg'] = "身份证号格式不正确!";
			} elseif (! $this->is_mobile_phone ( $mobile )) {
				$result ['state'] = - 1;
				$result ['msg'] = "手机号格式不正确!";
			} else {
				$user ['id'] = $id;
				$user ['name'] = $name;
				$user ['card'] = $card;
				$user ['mobile'] = $mobile;
				$user ['sex'] = $sex;
				$user ['updated_time'] = time ();
				$res = $this->wx_invite->save ( $user );
				if ($res != false) {
					$result ['state'] = 1;
					$result ['msg'] = "个人信息修改成功！";
				} else {
					$result ['state'] = - 1;
					$result ['msg'] = "个人信息修改失败！";
				}
			}
		}
		echo json_encode ( $result, true );
	}
	
	/**
	 * @info 我的员工
	 * 在职状态：1:申请中(默认)；2:未录取；3:在职；4:离职
	 */
	public function my_staff() {
		$this->check_is_invite ();
		$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
		$list = $this->wx_apply_job->alias ( "a" )->join ( "__PERSON__ as b ON b.id = a.person_id" )->join ( "__COMS__ as c ON c.id = a.com_id" )->where ( "a.invite_id=%d and a.job_state=%d", array (
				$uid,
				3 
		) )->field ( "b.name,b.mobile,a.created_time,a.updated_time,c.com_name" )->order ( "a.created_time DESC" )->limit ( 0 . ',' . $this->page_size )->select ();
		
		$qiutJobList = $this->wx_apply_job->alias ( "a" )->join ( "__PERSON__ as b ON b.id = a.person_id" )->join ( "__COMS__ as c ON c.id = a.com_id" )->where ( "a.invite_id=%d and a.job_state=%d", array (
				$uid,
				4 
		) )->field ( "b.name,b.mobile,a.created_time,a.updated_time,c.com_name" )->order ( "a.created_time DESC" )->limit ( 0 . ',' . $this->page_size )->select ();
		// $sql = $this->wx_apply_job->getLastSql();
		
		$no_applylist = $this->wx_apply_job->alias ( "a" )->join ( "__PERSON__ as b ON b.id = a.person_id" )->join ( "__COMS__ as c ON c.id = a.com_id" )->where ( "a.invite_id=%d and (a.job_state=%d or a.job_state=%d)", array (
				$uid,
				2,
				1 
		) )->field ( "b.name,b.mobile,a.created_time,a.updated_time,c.com_name" )->order ( "a.created_time DESC" )->limit ( 0 . ',' . $this->page_size )->select ();
		$sql = $this->wx_apply_job->getLastSql ();
		
		$list_count = count ( $list );
		$this->assign ( 'now_is_apply_size', $list_count );
		if ($list_count < $this->page_size) {
			$this->assign ( 'is_apply_has_more', 0 );
		} else {
			$this->assign ( 'is_apply_has_more', 1 );
		}
		
		$no_applylist_count = count ( $no_applylist );
		$this->assign ( 'now_no_apply_size', $no_applylist_count );
		if ($no_applylist_count < $this->page_size) {
			$this->assign ( 'no_apply_has_more', 0 );
		} else {
			$this->assign ( 'no_apply_has_more', 1 );
		}
		
		$quitJobList_count = count ( $qiutJobList );
		$this->assign ( 'now_quitJob_size', $quitJobList_count );
		if ($quitJobList_count < $this->page_size) {
			$this->assign ( 'quitJob_has_more', 0 );
		} else {
			$this->assign ( 'quitJob_has_more', 1 );
		}
		
		$this->assign ( 'list', $list );
		$this->assign ( 'no_applylist', $no_applylist );
		$this->assign ( 'quitJobList', $qiutJobList );
		$this->display ();
	}
	public function get_my_staff_list() {
		if (IS_AJAX) {
			$where = [ ];
			$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
			$where ['a.invite_id'] = $uid;
			$pageSize = I ( 'request.now_page_size', 0, 'intval' ); // 微信页面当前的显示数量
			$created_time = I ( 'request.created_time' );
			if ($created_time) {
				$where ["FROM_UNIXTIME(a.created_time, '%Y-%m-%d')"] = $created_time;
			}
			$type = I ( 'request.type' );
			switch ($type) {
				case 1 :
					$where ['a.job_state'] = 3;
					break;
				case 2 :
					$where ['a.job_state'] = array (
							'in',
							'1,2' 
					);
					break;
				case 3 :
					$where ['a.job_state'] = 4;
					break;
			}
			$list = $this->wx_apply_job->alias ( "a" )->join ( "__PERSON__ as b ON b.id = a.person_id" )->join ( "__COMS__ as c ON c.id = a.com_id" )->where ( $where )->field ( "b.name,b.mobile,a.created_time,a.updated_time,c.com_name" )->order ( "a.created_time DESC" )->limit ( $pageSize . ',' . $this->page_size )->select ();
			$sql = $this->wx_apply_job->getLastSql ();
			if (count ( $list ) < $this->page_size) {
				$has_more = 0;
			} else {
				$has_more = 1;
			}
			$this->assign ( 'list', $list );
			$content = $this->fetch ( 'staff_html' );
			$this->ajaxReturn ( array (
					'now_page_size' => $this->page_size + $pageSize,
					'content' => $content,
					'has_more' => $has_more 
			) );
		}
	}
	/**
	 * 我的财富
	 */
	public function my_money() {
		$this->check_is_invite ();
		
		$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
		$total_money = $this->getTotalMoney ( $uid );
		$this->assign ( "total_money", $total_money );
		$this->display ();
	}
	/**
	 * 提现规则
	 */
	public function tcash_rule() {
		$data = $this->wx_article->where ( array (
				"type" => 1 
		) )->find ();
		$this->assign ( "data", $data );
		$this->display ();
	}
	/**
	 * 接车点
	 */
	public function pick_point() {
		$data = $this->wx_article->where ( array (
				"type" => 2 
		) )->find ();
		$this->assign ( "data", $data );
		$this->display ();
	}
	/**
	 * 申请记录
	 */
	public function apply_record() {
		$this->check_is_invite ();
		$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
		$where ['moneyexp.invite_id'] = $uid;
		$file_arr = array (
				'moneyexp.id',
				'invite.name',
				'moneyexp.invite_id',
				'invite.mobile',
				'moneyexp.money',
				'bankinvite.bank_id',
				'bankinvite.bank_number',
				'moneyexp.state',
				'moneyexp.created_time' 
		);
		$list = $this->wx_money_exp->field ( implode ( ",", $file_arr ) )->join ( 'as moneyexp LEFT JOIN __INVITE__ as invite ON moneyexp.invite_id = invite.id' )->join ( 'LEFT JOIN __BANK_INVITE__ as bankinvite ON moneyexp.bank_invite_id = bankinvite.id' )->where ( $where )->order ( "moneyexp.created_time DESC" )->limit ( 0 . ',' . $this->page_size )->select ();
		if (count ( $list ) < $this->page_size) {
			$has_more = 0;
		} else {
			$has_more = 1;
		}
		$this->assign ( 'now_page_size', $this->page_size );
		$this->assign ( 'list', $list );
		$this->assign ( 'has_more', $has_more );
		$this->display ();
	}
	
	/**
	 * ajax 分页
	 */
	public function get_record_list() {
		$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
		if (IS_AJAX) {
			$where ['moneyexp.invite_id'] = $uid;
			$pageSize = I ( 'request.now_page_size', 0, 'intval' );
			$file_arr = array (
					'moneyexp.id',
					'invite.name',
					'moneyexp.invite_id',
					'invite.mobile',
					'moneyexp.money',
					'bankinvite.bank_id',
					'bankinvite.bank_number',
					'moneyexp.state',
					'moneyexp.created_time' 
			);
			$list = $this->wx_money_exp->field ( implode ( ",", $file_arr ) )->join ( 'as moneyexp LEFT JOIN __INVITE__ as invite ON moneyexp.invite_id = invite.id' )->join ( 'LEFT JOIN __BANK_INVITE__ as bankinvite ON moneyexp.bank_invite_id = bankinvite.id' )->where ( $where )->order ( "moneyexp.created_time DESC" )->limit ( $pageSize . ',' . $this->page_size )->select ();
			if (count ( $list ) < $this->page_size) {
				$has_more = 0;
			} else {
				$has_more = 1;
			}
			$this->assign ( 'list', $list );
			$content = $this->fetch ( 'record_list' );
			$this->ajaxReturn ( array (
					'now_page_size' => $this->page_size + $pageSize,
					'content' => $content,
					'has_more' => $has_more 
			) );
		}
	}
	
	/**
	 * 银行卡列表
	 */
	public function bank_list() {
		$user_type = I ( "user_type" );
		$uid = empty ( $_SESSION ['personID'] ) ? 0 : $_SESSION ['personID'];
		if (1 == $user_type) {
			/**
			 * 社招用户*
			 */
			$this->check_is_invite ();
			$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
		}
		$list = $this->wx_bank_invite->where ( array (
				"invite_id" => $uid,
				"user_type" => $user_type 
		) )->select ();
		$baseurl = $_SERVER ['SERVER_NAME'] ? "http://" . $_SERVER ['SERVER_NAME'] . "/" : "http://" . $_SERVER ['HTTP_HOST'] . "/";
		foreach ( $list as $k => $v ) {
			$len = strlen ( $v ['bank_number'] );
			$list [$k] ['bank_number'] = substr ( $v ['bank_number'], - 4 );
			$list [$k] ['img_url'] = $baseurl . "public/weixin/img/bank/" . $v ['bank_id'] . ".jpg";
		}
		$this->assign ( "list", $list );
		if (1 == $user_type) {
			/**
			 * 社招用户*
			 */
			$this->display ();
			exit ();
		}
		$this->display ( "bank_list_person" );
	}
	
	/**
	 * @info 选择银行卡
	 * 
	 * @author Mojianguo
	 *         @date 2017年1月17日 12:00:08
	 */
	public function bank_list_select() {
		$uid = empty ( $_SESSION ['personID'] ) ? 0 : $_SESSION ['personID'];
		$user_type = I ( "user_type" );
		if (1 == $user_type) {
			/**
			 * 社招用户*
			 */
			$this->check_is_invite ();
			$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
		}
		$list = $this->wx_bank_invite->where ( array (
				"invite_id" => $uid,
				"user_type" => $user_type 
		) )->select ();
		$baseurl = $_SERVER ['SERVER_NAME'] ? "http://" . $_SERVER ['SERVER_NAME'] . "/" : "http://" . $_SERVER ['HTTP_HOST'] . "/";
		foreach ( $list as $k => $v ) {
			$len = strlen ( $v ['bank_number'] );
			$list [$k] ['bank_number'] = substr ( $v ['bank_number'], - 4 );
			$list [$k] ['img_url'] = $baseurl . "public/weixin/img/bank/" . $v ['bank_id'] . ".jpg";
		}
		$this->assign ( "list", $list );
		if (empty ( $list )) {
			$this->redirect ( "bank_card", array (
					"firstAddBank" => true,
					"user_type" => $user_type 
			) );
			exit ();
		}
		if (1 == $user_type) {
			/**
			 * 社招用户*
			 */
			$this->display ();
			exit ();
		}
		$this->display ( "User/Person/bank_list_person_select" );
	}
	/**
	 * 银行卡删除
	 */
	public function bank_delete() {
		$user_type = I ( "user_type" );
		if (empty ( $user_type )) {
			/**
			 * 社招用户*
			 */
			$this->check_is_invite ();
		} else {
			$this->check_is_person ();
		}
		$id = empty ( $_POST ['id'] ) ? 0 : intval ( $_POST ['id'] );
		if ($this->wx_bank_invite->delete ( $id ) !== false) {
			$result ['state'] = 1;
		} else {
			$result ['state'] = - 1;
			$result ['msg'] = "删除失败!";
		}
		echo json_encode ( $result, true );
	}
	/**
	 * 添加银行卡
	 */
	public function bank_card() {
		$user_type = I ( "user_type" );
		/**
		 * 2：员工*
		 */
		$is_selectCard = I ( "is_selectCard" );
		/**
		 * 标识选择银行卡*
		 */
		$firstAddBank = I ( "firstAddBank" );
		/**
		 * 第一次添加银行卡标识*
		 */
		$this->assign ( "is_selectCard", $is_selectCard );
		$this->assign ( "firstAddBank", $firstAddBank );
		parent::dict_select ( array (
				array (
						'code' => 'BANK_TYPE',
						'name' => 'bank_id',
						'text' => '银行卡所属银行' 
				) 
		) );
		if (empty ( $user_type )) {
			/**
			 * 社招用户*
			 */
			$this->check_is_invite ();
			$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
			$data = $this->wx_invite->where ( array (
					"uid" => $uid 
			) )->find ();
			$this->assign ( "data", $data );
			$this->display ();
		} else {
			$this->check_is_person ();
			$uid = empty ( $_SESSION ['personID'] ) ? 0 : $_SESSION ['personID'];
			$data = $this->wx_person->where ( array (
					"id" => $uid 
			) )->find ();
			$this->assign ( "data", $data );
			$this->display ( "bank_card_person" );
		}
	}
	/**
	 * 添加银行卡提交
	 */
	public function bank_card_post() {
		$user_type = $_POST ['user_type'];
		$is_selectCard = $_POST ['is_selectCard'];
		$result ['is_selectCard'] = $is_selectCard;
		if (empty ( $user_type )) {
			$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
			$bankCard ['user_type'] = 1;
		} else {
			$uid = empty ( $_SESSION ['personID'] ) ? 0 : $_SESSION ['personID'];
			$bankCard ['user_type'] = 2;
		}
		$bank_id = $_POST ['bank_id'];
		$bank_number = $_POST ['bank_number'];
		if (empty ( $bank_id ) || empty ( $bank_number )) {
			$result ['state'] = - 1;
			$result ['msg'] = "必填信息不能为空!";
		} else {
			$str_msg = $this->verify_bank_card ( $bank_number );
			if ($str_msg != 1) {
				$result ['state'] = - 1;
				$result ['msg'] = $str_msg;
			} else {
				$bankinfo = $this->wx_bank_invite->where ( array (
						"bank_number" => $bank_number,
						"invite_id" => $uid 
				) )->find ();
				if (empty ( $bankinfo )) {
					$bankCard ['bank_id'] = $bank_id;
					$bankCard ['bank_number'] = $bank_number;
					$bankCard ['invite_id'] = $uid;
					$bankCard ['created_time'] = time ();
					$res = $this->wx_bank_invite->add ( $bankCard );
					if ($res != false) {
						$result ['state'] = 1;
						$result ['msg'] = "绑定成功!";
					} else {
						$result ['state'] = - 1;
						$result ['msg'] = "绑定失败!";
					}
				} else {
					$result ['state'] = - 1;
					$result ['msg'] = "该银行卡已经绑定过了!";
				}
			}
		}
		echo json_encode ( $result, true );
	}
	/**
	 * 申请提现
	 */
	public function tcash() {
		$this->check_is_invite ();
		$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
		$bankID = I ( "bankID" );
		if (! empty ( $bankID )) {
			/**
			 * 获取选中的银行卡信息*
			 */
			$bank = $this->wx_bank_invite->field ( array (
					'id',
					'bank_id',
					'bank_number' 
			) )->where ( array (
					"id" => $bankID 
			) )->find ();
		} else {
			$bank = $this->wx_bank_invite->where ( array (
					"invite_id" => $uid 
			) )->field ( array (
					'id',
					'bank_id',
					'bank_number' 
			) )->order ( 'created_time desc' )->find ();
			if (empty ( $bank )) {
				/**
				 * *还没有添加银行卡
				 */
				$this->redirect ( "bank_card", array (
						"firstAddBank" => true 
				) );
				exit ();
			}
		}
		$this->assign ( "bank", $bank );
		$this->display ();
	}
	/**
	 * 申请提现提交
	 */
	public function tcash_post() {
		$money = empty ( $_POST ['money'] ) ? 0 : intval ( $_POST ['money'] );
		if ($money == 0 || $money < 100) {
			$result ['state'] = - 1;
			$result ['msg'] = "每次提现，金额不能少于100!";
		} else {
			$bank_invite_id = $_POST ['bank_invite_id'];
			// $msg = $_POST['msg'];
			$uid = empty ( $_SESSION ['uid'] ) ? 0 : $_SESSION ['uid'];
			if ($money == 0 || empty ( $bank_invite_id )) {
				$result ['state'] = - 1;
				$result ['msg'] = "必填信息不能为空!";
			} else {
				$total_money = intval ( $this->getTotalMoney ( $uid ) );
				if ($total_money - $money < 0) {
					$result ['state'] = - 1;
					$result ['msg'] = "您的余额不足，不能提现!";
				} else {
					$tcash ['money'] = $money;
					$tcash ['bank_invite_id'] = $bank_invite_id;
					$tcash ['invite_id'] = $uid;
					$tcash ['created_time'] = time ();
					// $tcash['msg'] = $msg;
					$res = $this->wx_money_exp->add ( $tcash );
					if ($res != false) {
						$result ['state'] = 1;
						$result ['msg'] = "提现成功!";
					} else {
						$result ['state'] = - 1;
						$result ['msg'] = "提现失败!";
					}
				}
			}
		}
		echo json_encode ( $result, true );
	}
	
	/**
	 * **
	 * @info 用户中心
	 * 根据openID判断用户状态：
	 * 未绑定：进行绑定操作；
	 * 未登录：进行登录操作；
	 * 已登录：获取sessionID
	 * 判断用户在职状态，在职根据在职天数获取借支金额
	 * 进入用户中心界面
	 * 
	 * @author Mojianguo
	 *         @date 二〇一七年一月七日
	 */
	public function userCenter() {
		$this->check_is_borrow ();
		$borrowCount = 0; // 借支限额
		$jobState = - 1; // 在职状态
		$jobDesc = "不在职"; // 在职描述
		$personID = empty ( $_SESSION ['personID'] ) ? 0 : $_SESSION ['personID'];
		$openID = empty ( $_SESSION ['openID'] ) ? 0 : $_SESSION ['openID'];
		$wxUser = $this->wx_user->where ( array (
				"open_id" => $openID 
		) )->find ();
		$bool = true;
		if (empty ( $personID ) || $personID == 0) {
			/**
			 * 员工登录
			 */
			$user = $this->wx_person->where ( array (
					"open_id" => $openID 
			) )->find ();
			if (! empty ( $user ) && count ( $user ) > 0) {
				/**
				 * 登录成功
				 */
				$personID = $user ["id"];
				$_SESSION ['personID'] = $personID;
			} else { // //登录失败
				$bool = false;
			}
		}
		if ($bool) {
			$applyJobs = $this->wx_apply_job->where ( array (
					"person_id" => $personID 
			) )->select ();
			foreach ( $applyJobs as $applyJob ) {
				if (3 == $applyJob ['job_state']) { // 在职记录
					$borrowCount = $this->getBorrowNum ( $personID ) ['maxVaule'];
					$jobState = 3; // 入职状态
					$jobDesc = "在职"; // 入职描述
					break;
				} else { // //其他状态
					$jobState = $applyJob ['job_state']; // 入职状态
					$jobDesc = C ( "PERSON_APPLY_STATE" ) [$jobState] ['dict_text']; // 入职描述
				}
			}
		}
		/**
		 * *START 银行卡绑定数量*
		 */
		// $cardNum = $this->wx_bank_invite->where(array("invite_id" =>$personID))->count();
		// $this->assign("cardNum",$cardNum);
		/**
		 * *END 银行卡绑定数量*
		 */
		
		$this->assign ( "borrowCount", $borrowCount );
		$this->assign ( "jobState", $jobState );
		$this->assign ( "jobDesc", $jobDesc );
		$this->assign ( "user", $wxUser );
		$this->display ( "userCenter" );
		exit ();
	}
	/**
	 * **
	 * @info 员工个人中心
	 * 
	 * @author Mojianguo
	 *         @date 2017年1月8日
	 */
	public function personInfo() {
		$personID = empty ( $_SESSION ['personID'] ) ? 0 : $_SESSION ['personID'];
		if (! $this->check_is_person ( $personID )) {
			$this->display ( "User/bindUserIndex" );
			exit ();
		} else {
			$data = $this->wx_person->where ( array (
					"id" => $personID 
			) )->find ();
			$data ['sex'] = C ( "USER_SEX" ) [$data ['sex']] ['dict_text'];
			$this->assign ( "data", $data );
			$this->display ();
			exit ();
		}
	}
	/**
	 * *
	 * @info 用户绑定业务操作
	 */
	public function bindUser() {
		$mobile = $_POST ['mobile'];
		$card = $_POST ['card'];
		$mobile_code = $_POST ['mobile_code'];
		if (empty ( $mobile ) || empty ( $mobile_code ) || empty ( $card )) {
			$result ['state'] = - 1;
			$result ['msg'] = "必填信息不能为空!";
		} else {
			if (! $this->is_mobile_phone ( $mobile )) {
				$result ['state'] = - 1;
				$result ['msg'] = "手机号格式不正确!";
			} elseif ($this->idcard_verify_number ( $card )) {
				$result ['state'] = - 1;
				$result ['msg'] = "身份证号码格式不正确!";
			} else {
				$record = $this->get_validate_record ( $mobile );
				$mobile_phone = $_SESSION ["mobile_phone"];
				/* 手机验证码检查 */
				if (empty ( $mobile_code )) {
					$result ['state'] = - 1;
					$result ['msg'] = "手机验证码不能为空!";
				} else if ($mobile != $mobile_phone) { // 检查发送短信验证码的手机号码和提交的手机号码是否匹配
					$result ['state'] = - 1;
					$result ['msg'] = "发送短信验证码的手机号码和提交的手机号码不匹配!";
				} else if ($record ['record_code'] != $mobile_code) { // 检查验证码是否正确
					$result ['state'] = - 1;
					$result ['msg'] = "手机验证码不正确!";
				} else if ($record ['expired_time'] < time ()) { // 检查过期时间
					$result ['state'] = - 1;
					$result ['msg'] = "验证码已经过期!";
				} else { // /进行手机绑定业务
					$persons = $this->wx_person->where ( array (
							"card" => $card 
					) )->find ();
					if (empty ( $persons )) {
						$result ['state'] = - 1;
						$result ['msg'] = "该身份证号码未录入系统，请核实!";
					} else {
						$openID = empty ( $_SESSION ['openID'] ) ? 0 : $_SESSION ['openID'];
						$data ['open_id'] = $openID;
						$data ['mobile'] = $mobile;
						$personID ['id'] = $persons ['id'];
						$num = $this->wx_person->where ( $personID )->save ( $data );
						if ($num !== false) {
							$_SESSION ['personID'] = $persons ['id'];
							$result ['state'] = 1;
						} else {
							$result ['state'] = - 1;
							$result ['msg'] = "绑定失败，请联系管理员!";
						}
					}
				}
			}
		}
		echo json_encode ( $result, true );
	}
	/**
	 * **
	 * @info 借支申请index
	 * 
	 * @author Mojianguo
	 *         @date 2017年1月9日
	 */
	public function borrowRquestIndex() {
		$personID = empty ( $_SESSION ['personID'] ) ? 0 : $_SESSION ['personID'];
		if (! $this->check_is_borrow ( $personID )) {
			$this->display ( 'User/notOnJob' );
			die ();
		}
		$personInfo = $this->wx_person->where ( array (
				"id" => $personID 
		) )->find ();
		$result = $this->getBorrowNum ( $personID );
		$personInfo ['maxValue'] = $result ['maxVaule'];
		$personInfo ['comlist'] = $result ['comlist'];
		/**
		 * 员工在职企业列表*
		 */
		parent::dict_radio ( array (
				array (
						'code' => 'PAYMONEY_TYPE',
						'name' => 'type',
						'text' => '收款类型' 
				) 
		) );
		$bankID = I ( "bankID" );
		if (! empty ( $bankID )) {
			/**
			 * 获取选中的银行卡信息*
			 */
			$bank = $this->wx_bank_invite->field ( array (
					'id',
					'bank_id',
					'bank_number' 
			) )->where ( array (
					"id" => $bankID 
			) )->find ();
		} else {
			$bank = $this->wx_bank_invite->where ( array (
					"invite_id" => $personID 
			) )->field ( array (
					'id',
					'bank_id',
					'bank_number' 
			) )->order ( 'created_time desc' )->find ();
		}
		$this->assign ( "bank_invite_id", $bank ['id'] );
		$this->assign ( "bank_number", $bank ['bank_number'] );
		$this->assign ( "bank_id", $bank ['bank_id'] );
		$this->assign ( "personInfo", $personInfo );
		$this->display ();
		exit ();
	}
	/**
	 * **
	 * @info 借支申请
	 */
	public function borrowRequest() {
		$reason = I ( "reason" );
		$comID = I ( "comID" );
		$num = I ( "num" );
		$type = I ( "type" );
		$bank_id = I ( "bank_id" );
		/**
		 * 收款银行绑定ID
		 */
		$personID = empty ( $_SESSION ['personID'] ) ? 0 : $_SESSION ['personID'];
		if (empty ( $comID ) || empty ( $num ) || empty ( $type ) || "undefined" == $type || "undefined" == $comID) {
			$result ['state'] = - 1;
			$result ['msg'] = "必填信息不能为空!";
		} else if (! is_numeric ( $num )) {
			$result ['state'] = - 1;
			$result ['msg'] = "申请金额必须为正整数!";
		} else {
			$maxValue = $this->getBorrowNumByComID ( $personID, $comID );
			if ($num > $maxValue) {
				$result ['state'] = - 1;
				$result ['msg'] = "申请金额超出限额，请隔天重试或修改数目";
			} else { // ///开始业务操作
				$lastDay = ($maxValue - $num) / SUM_NUM;
				/**
				 * 需要推迟的天数*
				 */
				$lastDay -= $lastDay * 2;
				/**
				 * 转换为负数
				 */
				// 时间最后一次借支时间 = 当天时间 - [(当日最大额度 - 申请额度)/SUM_NUM]
				$last_requestdate = strtotime ( "$lastDay day" );
				$data = array (
						"personID" => $personID, // 员工ID
						"comID" => $comID, // 公司ID
						"type" => $type, // 收款方式
						"num" => $num, // 借支金额
						"requestDate" => time (), // 申请时间
						"last_requestdate" => $last_requestdate,
						/**
						 * 实际最后一次借支时间
						 */
						"reason" => $reason, // 借支理由
						"bank_id" => $bank_id 
				)/**
				 * 收款银行卡ID*
				 */
				;
				$res = $this->borrow->add ( $data );
				if ($res != false) {
					$result ['state'] = 1;
				} else {
					$result ['state'] = - 1;
					$result ['msg'] = "申请失败,请重试!";
				}
			}
		}
		echo json_encode ( $result, true );
	}
	/**
	 * **
	 * @info 借支列表Init
	 */
	public function borrowList() {
		$personID = empty ( $_SESSION ['personID'] ) ? 0 : $_SESSION ['personID'];
		$pageSize = 0;
		if (IS_AJAX) {
			$pageSize = I ( 'request.now_page_size', 0, 'intval' );
		}
		$where ['borrow.personID'] = $personID;
		$file_arr = array (
				'borrow.id',
				'borrow.comID',
				'borrow.type',
				'borrow.num',
				'borrow.requestDate',
				'borrow.state',
				'borrow.reason',
				'com.com_name' 
		);
		$list = $this->borrow->field ( implode ( ",", $file_arr ) )->join ( 'as borrow LEFT JOIN __COMS__ as com ON com.id = borrow.comID' )->where ( $where )->order ( "borrow.requestDate DESC" )->limit ( $pageSize . ',' . $this->page_size )->select ();
		if (count ( $list ) < $this->page_size) {
			$has_more = 0;
		} else {
			$has_more = 1;
		}
		$this->assign ( 'list', $list );
		if (IS_AJAX) {
			$content = $this->fetch ( 'borrow_list' );
			$this->ajaxReturn ( array (
					'now_page_size' => $this->page_size + $pageSize,
					'content' => $content,
					'has_more' => $has_more 
			) );
		} else {
			$this->assign ( 'now_page_size', $this->page_size );
			$this->assign ( 'has_more', $has_more );
			$this->display ();
		}
	}
}

